package weeny.wordle.pre;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import prefuse.action.layout.Layout;
import prefuse.render.LabelRenderer;
import prefuse.render.Renderer;
import prefuse.visual.VisualItem;
import wordle.layout.LabelWordle;
import wordle.layout.Wordle;
import wordle.layout.WordleAlgorithm;

import static prefuse.render.Renderer.DEFAULT_GRAPHICS;


/**
 * Layout all the labels using wordle algorithm
 * 
 * @author weeny
 */
public class WordleLabelLayout extends Layout{

	public WordleLabelLayout(String group) {
		super(group);
	}
    
	private void setLabelVisualPos(Wordle symbol){
		LabelWordle label = (LabelWordle) symbol;
		Point2D location = label.getLocation();
		VisualItem vi = (VisualItem) label.data;
		Rectangle2D glyphBound = label.getShape().getBounds2D();

		float size = (float) (vi.getFont().getSize2D()*vi.getSize());
		Font font = vi.getFont().deriveFont(size);
        FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(font);
        Rectangle2D strBound = fm.getStringBounds(label.text, DEFAULT_GRAPHICS);
        /*
         * location is the glyph's location, i.e.:
         * x = the minimum x coordinate of the glyph
         * y = the baseline of the text string
         */
        vi.setX(location.getX()+glyphBound.getX()+strBound.getWidth()/2);
        vi.setY(location.getY()+fm.getDescent()-strBound.getHeight()/2);
	}
	public void run(double frac) {
		List<LabelWordle> list = new ArrayList<LabelWordle>();
		for (Iterator<VisualItem> it = m_vis.items(getGroup()); it.hasNext();) {
			VisualItem vi = it.next();
			Renderer ren = m_vis.getRenderer(vi);
			if (!(ren instanceof LabelRenderer)) {
				continue;
			}
			LabelRenderer lRen = (LabelRenderer) ren;
			String text = vi.getString(lRen.getTextField());
			if (text == null) {
				continue;
			}
			double weight = vi.getSize()*vi.getFont().getSize();
			Font font = vi.getFont().deriveFont((float) weight);
			LabelWordle word = new LabelWordle(text, font, 0, vi);
			list.add(word);
		}
		WordleAlgorithm alg = new WordleAlgorithm(getLayoutBounds());
		alg.calc(list);
		for(LabelWordle word : list){
			setLabelVisualPos(word);
		}
	}
}